<?php

/**
 * Configuration loader from PHP arrays
 * 
 * @package Rapide_Config
 */
class Rapide_Config_Loader_PhpArray implements Rapide_Config_Loader_Interface
{
	/**
	 * Loads configuration from given file name
	 * 
	 * Path to the file can be relative. In this case, method will try to load file
	 * from default configuration directory.
	 *
	 * @throws Rapide_Config_Loader_PhpArray_Exception if file or configuration array inside does not exist
	 * @param string $sConfigFile file name
	 * @return array
	 */
	public static function load($sConfigFile)
	{
		// Check if only file name was passed (without directory)
		// and load this file from default directory

		$sRelConfigFile = _DIR_CONFIGURATIONS . '/' . $sConfigFile;

		if(is_readable($sRelConfigFile))
		{
			require $sRelConfigFile;
			$sRecursiveString = substr($sConfigFile, 0, -4);
		}
		elseif(is_readable($sConfigFile))
		{
			require $sConfigFile;
			$sRecursiveString = substr(basename($sConfigFile), 0, -4);
		}
		else
		{
			$sError = sprintf('Config file %s does not exist', $sConfigFile);
			throw new Rapide_Config_Loader_PhpArray_Exception($sError);
		}

		if(!isset($aConfig) || !is_array($aConfig))
		{
			$sError = sprintf('Config array in file %s does not exist', $sConfigFile);
			throw new Rapide_Config_Loader_PhpArray_Exception($sError);
		}

		return self::_getRecursiveArray($sRecursiveString, $aConfig);
	}

	private static function _getRecursiveArray($sString, $aData)
	{
		$aEntries = explode('/', $sString);

		$aTemp = $aData;
		$aData = array();

		for($i = count($aEntries) - 1; $i >= 0; $i--)
		{
			$aData = array();
			$aData[$aEntries[$i]] =	$aTemp;
			$aTemp = $aData;
		}

		return $aData;
	}
}

?>